package com.cskaoyan.demo6.servlet;

import com.cskaoyan.demo6.common.CommonServlet;
import com.cskaoyan.demo6.util.JacksonUtil;
import lombok.SneakyThrows;

import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

@WebServlet("/body/*")
public class BodyServlet extends CommonServlet {
    @SneakyThrows
    public void json(HttpServletRequest request, HttpServletResponse response) {
        PrintWriter writer = response.getWriter();
        HashMap<String, Object> map = new HashMap<>();
        Object data = map.put("data", "hello");
        map.put("message","success");
        map.put("code", 0);
        String jsonStr = JacksonUtil.write(map);
        writer.println(jsonStr); // jsonStr → 出现在响应体
    }

    // image
    // localhost:8080/demo6/body/image?name=banner.png
    // 访问d:/app2/路径下图片 banner.png
    public void image(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String path = "d:/app2";
        String fileName = request.getParameter("name");
        File file = new File(path, fileName);
        FileInputStream inputStream = new FileInputStream(file);

        //响应报文的响应体提供文件的字节数据    字节输出流
        ServletOutputStream outputStream = response.getOutputStream();
        int lenght=0;
        byte[] bytes = new byte[1024];
        while ((lenght = inputStream.read(bytes)) != -1) {
            outputStream.write(bytes,0,lenght);
        }
        inputStream.close();
        outputStream.close();
    }
}
